import React, { CSSProperties } from 'react';
import i18n from 'i18n-js';
import { View, Text, Image } from "@tarojs/components";
import { List, Loading } from '@taroify/core';
import PageModel from '@/utils/PageModel'
import FlexScrollView from '@/components/FlexScrollView';
import noneIcon from '@/assets/images/billing_record_icon_default.png';
import {
  GStyleSheet,
} from '@/utils/DarkMode';

interface IProps {
  id: string;
  style?: CSSProperties;
  query: ({ current }: { current: number }) => Promise<void>; // 查询方法
  pageModel: PageModel<any>;
  renderItem: ({ item, index }: { item: any, index: number }) => any;
}


const dstyles = GStyleSheet.create({
  noneBox: {
    marginTop: 100,
    textAlign: 'center',
  },
  noneRecord: {
    marginTop: 15,
    backgroundColor: 'rgba(0,0,0,0)',
    color: '#ccc',
    textAlign: 'center',
  },
});


export default class PageList extends React.Component<IProps> {

  lock = false;

  loading = false;

  state = {
    loading: false,
  }

  componentDidMount() {
    console.log('componentDidMount')
    this.queryData(1);
  }

  queryData = async (current: number) => {
    if (this.loading) {
      return;
    }
    this.loading = true;
    this.setState({ loading: true });
    const { query } = this.props;
    await query({ current });
    this.setState({ loading: false }, () => {
      this.loading = false;
      this.lock = false;
    });
  }

  onEndReached = () => {
    const { pageModel } = this.props;
    const hasMore = pageModel.haveMore;
    if (!hasMore) {
      return;
    }
    console.log('onEndReached', this.lock, hasMore);
    if (this.lock) {
      return;
    }
    this.lock = true;
    if (this.loading) {
      return;
    }
    this.queryData(pageModel.current + 1);
  }

  render() {
    const { loading } = this.state;
    const { pageModel, renderItem, id, style } = this.props;
    const list = pageModel.records;
    const hasMore = pageModel.haveMore;
    const styles = dstyles.style;
    // console.log('list', list);
    return (
      list.length > 0 ?
        <FlexScrollView
          id={id}
          style={style}
          onScrollToLower={this.onEndReached}
        >
          {
            list.map((item, index) => renderItem({ item, index }))
          }
          <List.Placeholder>
            {loading && <Loading>{i18n.t('LOADING')}</Loading>}
            {(!loading && !hasMore) && i18n.t('NO_MORE')}
          </List.Placeholder>
        </FlexScrollView> : (
          <View style={styles.noneBox}>
            <View>
              <Image src={noneIcon} style={{ width: 172, height: 102 }} />
            </View>
            <View>
              <Text style={styles.noneRecord}>{i18n.t('NO_RECORD')}</Text>
            </View>
          </View>
        )
    );
  }
}
